package com.nikmesoft.android.referendumfriend.activities;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.models.Activity_Group;
import com.nikmesoft.android.referendumfriend.models.ItemMyActivities;
import com.nikmesoft.android.referendumfriend.models.MyGroupImage;
import com.nikmesoft.android.referendumfriend.service.ActivityHobbyHandler;
import com.nikmesoft.android.referendumfriend.service.ImageDownloader;
import com.nikmesoft.android.referendumfriend.service.LoginHandler;
import com.nikmesoft.android.referendumfriend.utils.CommonUtil;

public class MyActivities_detail extends BaseActivity {

	ItemMyActivities myacti=null;
	private ProgressDialog dialog;
	private WSLoader loader;
	private WSLoaderActivity loader1;
	Activity_Group user1 = new Activity_Group();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_myactivities_detail);
		Bundle bun=(Bundle)getIntent().getExtras();
		myacti=(ItemMyActivities)bun.getSerializable("mydetail");
		if (myacti!=null) {
		TextView tx=(TextView)findViewById(R.id.status_detail);
		TextView txlike=(TextView)findViewById(R.id.like_detail);
		TextView txdislike=(TextView) findViewById(R.id.tv_dislike);
		TextView txgroupname=(TextView) findViewById(R.id.groupname_detail);
		txgroupname.setText(myacti.getName_hobby());
		tx.setText(myacti.getContent());
		txlike.setText(myacti.getLike());
		txdislike.setText(myacti.getDislike());
		dialog = new ProgressDialog(this);
		dialog.setMessage("Loading...Please wait...");
		}
	}
	public void groupname(View v)
	{
		
		if (loader1 == null || loader1.isCancelled()
				|| loader1.getStatus() == Status.FINISHED) {
			loader1 = new WSLoaderActivity();
			loader1.execute(String.valueOf(LoginHandler.result.getId()),myacti.getId_hobby(),"1");
		}
	}
	public void callBack(View v)
	{
		finish();
	}
	public void toad(String x)
	{
		
		CommonUtil.toastNotify(this,x);
	}
	public void like(View v) {
		String id_acti=myacti.getId();
		TextView tvlike=(TextView)findViewById(R.id.like_detail);
		if (loader == null || loader.isCancelled()
				|| loader.getStatus() == Status.FINISHED) {
			loader = new WSLoader();
			loader.execute(String.valueOf(LoginHandler.result.getId()),id_acti,"1");
		}
		int i=Integer.parseInt(tvlike.getText().toString())+1;
		tvlike.setText(String.valueOf(i));
		
		}
	public void unlike(View v) {
	
		TextView tvunlike=(TextView)findViewById(R.id.tv_dislike);
		String id_acti=myacti.getId();
		if (loader == null || loader.isCancelled()
				|| loader.getStatus() ==  Status.FINISHED) {
			loader = new WSLoader();
			loader.execute(String.valueOf(LoginHandler.result.getId()),id_acti,"-1");
		}
		int i=Integer.parseInt(tvunlike.getText().toString())+1;
		tvunlike.setText(String.valueOf(i));
		}
	private String callWSActivity(String name1,String name2,String name3) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<getActivities soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<GetActivitiesRequest xsi:type=\"rdf:GetActivitiesRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<id_user xsi:type=\"xsd:int\">"
				+ name1
				+ "</id_user>"
				+ "<id_hobby xsi:type=\"xsd:int\">"
				+ name2
				+ "</id_hobby>"
				+ "<page xsi:type=\"xsd:int\">"
				+ name3
				+ "</page>"
				+ "</GetActivitiesRequest>"
				+ "</getActivities>"
				+ "</soapenv:Body>" + "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}
	public void loadavatar()
	{
		MyGroupImage.ar_avatar=new ArrayList<Bitmap>();
		try {
		for (int i=0;i<user1.getArr().size();i++)
		{
			
			Bitmap bit=ImageDownloader.downloadImage(user1.get(i).getAvatar_user());
			MyGroupImage.ar_avatar.add(bit);
		}
		}catch(Exception e)
		{
			toad("Loi load anh");
		}
	}
	private Activity_Group xmlParserActivity(String strXml) {
		byte xmlBytes[] = strXml.getBytes();
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				xmlBytes);
		SAXParserFactory saxPF = SAXParserFactory.newInstance();
		SAXParser saxParser;
		try {
			saxParser = saxPF.newSAXParser();
			XMLReader xr = saxParser.getXMLReader();
			ActivityHobbyHandler handler = new ActivityHobbyHandler();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(byteArrayInputStream));
			return handler.getResult();

		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	private class WSLoaderActivity extends AsyncTask<String, Integer, Activity_Group> {

		@Override
		protected Activity_Group doInBackground(String... params) {
			Activity_Group us = xmlParserActivity(callWSActivity(params[0],params[1],params[2]));
			user1 =us;
			loadavatar();
			return us;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Activity_Group result) {
			super.onPostExecute(result);	
			dialog.dismiss();
			Intent intent = new Intent(MyActivities_detail.this, activity_post_hobby.class);
			Bundle bun=new Bundle();
			bun.putSerializable("user1", user1);
			intent.putExtras(bun);
			startActivity(intent);
			
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}
	private Void callWS_FB(String id_user, String id_activity, String action) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<addFB soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<AddFBRequest xsi:type=\"rdf:AddFBRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<id_user xsi:type=\"xsd:int\">"+id_user+"</id_user>"
				+ "<id_activity xsi:type=\"xsd:int\">"+id_activity+"</id_activity>"
				+ "<action xsi:type=\"xsd:int\">"+action+"</action>"
				+ "</AddFBRequest>"
				+ "</addFB>"
				+ "</soapenv:Body>"
				+ "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		Void a=null;
		return a;
	}

	private class WSLoader extends AsyncTask<String, Integer, Void> {

		@Override
		protected Void doInBackground(String... params) {
			return callWS_FB(params[0], params[1], params[2]);

		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}

}
